package com.sz.service.frame;

import com.sz.exception.SaveException;
import com.sz.lucene.TikuIndex;
import com.sz.pojo.frame.Tiku;
import com.sz.util.ToolStr;
import org.apdplat.word.analysis.SimpleTextSimilarity;
import org.apdplat.word.analysis.TextSimilarity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service("tikuService")
public class TikuService extends BaseService<Tiku> {
    @Autowired
    private TikuIndex tikuIndex;
    @Autowired
    private HttpServletRequest httpServletRequest;

    public TikuService() {
        super(Tiku.class);
    }

    /**
     * 添加或者更新表结构
     *
     * @param t
     * @throws SaveException
     */
    public void save(Tiku t) {
        if (t == null) {
            throw new SaveException("传参错误，请检查");
        }
        try {
            if (t.getId() == null || t.getId() <= 0) {
                //判断数据库中是否存在相同的问题，答案如果问题，答案完全相同那么就不存
                List<Tiku> tikuList = exist(t);
                if (ToolStr.isEmpty(tikuList)) {
                    baseDao.save(t);
                    tikuIndex.addIndex(httpServletRequest, t);
                } else {
                    tikuIndex.updateIndex(httpServletRequest, tikuList.get(0));
                }
            } else {
                Tiku vo = this.load(t.getId(), true);
                vo.copy(t);
                baseDao.update(vo);
                tikuIndex.updateIndex(httpServletRequest, t);
            }
        } catch (Exception e) {
            throw new SaveException(e.getMessage());
        }
    }

    private List<Tiku> exist(Tiku tiku) {
        String q = tiku.getQuesetion();
        String a = tiku.getAnswer();
        Map<String, Object> map = new HashMap<>();
        if (ToolStr.isEmpty(q) && ToolStr.isEmpty(a)) {
            throw new SaveException("插入的问题为空");
        }
        map.put("quesetion = ", q);
        map.put("answer = ", a);
        List<Tiku> list = find4Params(map);
        return list;
    }

    // @Override
    public void remove(String ids) {
        removeMultiple(ids);
        List<String> idlist = Arrays.asList(ids.split(","));
        idlist.forEach(id -> {
            try {
                tikuIndex.deleteIndex(httpServletRequest, id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

    public Tiku webfind(String question) {
        List<Tiku> tikulist = findAll();
        ArrayList<Double> similarlist = new ArrayList<>();
        tikulist.forEach(tiku -> {
            TextSimilarity textSimilarity = new SimpleTextSimilarity();
            similarlist.add(textSimilarity.similarScore(question, tiku.getQuesetion()));
        });

        Double max = similarlist.stream().max(Comparator.comparingDouble(u -> u)).get();

        System.out.println();

        // similarlist.stream().

        return null;
    }
}
